<template>
  <el-select
    style="width: 100%"
    v-model="available_zone_id"
    placeholder="请选择可用区"
    @change="fnAzChange"
  >
    <el-option
      v-for="item in az_list"
      :key="item?.available_zone_id"
      :label="item?.available_zone_name"
      :value="item?.available_zone_id"
    ></el-option>
  </el-select>
</template>

<script>
import GoodsService from '@/service/eks/goods';
import { computed, ref, watch } from 'vue';
export default {
  props: {
    modelValue: {
      type: String,
      default: '',
      required: true
    },
    available_zone_name: {
      type: String,
      default: '',
      required: false
    },
    visible: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  emits: ['update:modelValue', 'update:available_zone_name', 'getAllFamily'],
  setup(props, { emit }) {
    const available_zone_id = computed({
      get() {
        return props.modelValue
      },
      set(val) {
        emit('update:modelValue', val)
      }
    });
    const available_zone_name = ref('')
    const az_list = ref([]);

    const getRegions = () => {
      GoodsService.getRegions().then(res => {
        if (res.code === 'Success') {
          let list = [];
          res.data.forEach(el => {
            if (el?.region_list) {
              el.region_list.forEach(item => {
                if (item?.available_zone_list) {
                  item.available_zone_list.forEach(item2 => {
                    list.push(item2)
                  })
                }
              })
            }
          });
          az_list.value = list;
          available_zone_id.value = list[0]?.available_zone_id;
          available_zone_name.value = list[0]?.available_zone_name;
          emit('getAllFamily');
        }
      })
    }
    const fnAzChange = (val) => {
      if(val) {
        available_zone_name.value = az_list.value.find(el => el?.available_zone_id === val)?.available_zone_name
        emit('update:available_zone_name', available_zone_name.value)
      }
    }

    watch(() => props.visible, (newVal, oldVal) => {
      if (newVal) {
        getRegions()
      }
    }, {
      immediate: true
    })

    return {
      available_zone_id,
      available_zone_name,
      az_list,
      getRegions,
      fnAzChange
    }
  }
}
</script>

<style lang="scss" scoped>
</style>